<?php
/**
 * TinyCorePHP Control基类
 * @author 	kelecode@gmail.com
 * @date 	2013-02-17
 */
class Control{
	public $vars = array();
	public $tmpl = 'template';

	public function __construct(){
		//
	}
	
	public function assign($key,$val){
		$this->vars[$key] = $val;
	}
	
	public function display($tmpl,$path=null){
		if(is_array($this->vars)) {
        	extract($this->vars, EXTR_SKIP);
      	}
		$theme = trim(C('theme'));
		$theme = empty($theme) ? 'default' : $theme; 
		$class_name = get_class($this);
		$path = empty($path) ? substr($class_name,0,-7) : $path;
      	$path = strtolower($path);		
		$temp = explode('.',$path);
		foreach($temp as $k => $v){
			$temp[$k] = trim($v);
		}
		$component = (string)trim(getgpc('com'));
		if( ! empty($component) ){
			//当需要在组件中调用根目录模板文件时,可在$path参数值前可加上'@.' 		
			if('@' == $temp[0]){
				$path = $temp[1];
				$file = APP_ROOT . '/' . $this->tmpl . '/' . $theme . '/' . $path . '/' . $tmpl.'.php';
			}else{
				$file = APP_ROOT . '/component/com_' . strtolower($component) .'/' . $this->tmpl . '/' . $theme . '/' . $path . '/' . $tmpl.'.php';
			} 
		}else{
			if('com' == $temp[0]){
				$component = $temp[1];
				$path = $temp[2];
				$file = APP_ROOT . '/component/com_' . $component .'/' . $this->tmpl . '/' . $theme . '/' . $path . '/' . $tmpl . '.php';
			}else{
				$file = APP_ROOT . '/' . $this->tmpl . '/' . $theme . '/' . $path . '/' . $tmpl.'.php';
			}
		}
		
		if(file_exists($file)){
      		@include $file;
			//调试信息
			if(C('app_debug')){
				$e = array();
				$trace = debug_backtrace();
				$e['message'] = $error;
				$e['file'] = $trace[0]['file'];
				$e['class'] = $trace[0]['class'];
				$e['function'] = $trace[0]['function'];
				$e['line'] = $trace[0]['line'];
				$traceInfo = '';
				$time = date("Y-m-d H:i:s");
				foreach($trace as $t){
					$traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
					$traceInfo .= $t['class'].$t['type'].$t['function'].'(';
					$traceInfo .= implode(', ', $t['args']);
					$traceInfo .= ")<br/>";
				}
				$e['trace']  = $traceInfo;
				$_trace = $e;
				include 'template/trace.tpl.php';
			}
      	}else{
      		die('template file is not found.');
      	}
	}
}